package net.asfun.jvalog.action;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.asfun.jvalog.domain.Comment;
import net.asfun.jvalog.except.InteractException;
import net.asfun.jvalog.http.RequestUtil;
import net.asfun.jvalog.misc.Checker;
import net.asfun.jvalog.misc.Filter;
import net.asfun.jvalog.view.PagerInfo;

public class CommentAction extends BaseAction{
	
	/**
	 * list recent comments as page
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	public void index(HttpServletRequest req, HttpServletResponse resp) throws IOException{
		int page = RequestUtil.getIntParam(req, "page");
		PagerInfo pager = new PagerInfo();
		pager.setIndex(page);
		this.assign("comments", Comment.listAll(pager));
		this.assign("pager", pager);
		this.render("admin/comments.html", resp);
	}
	
	/**
	 * delete one or more comments
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	public void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		Long[] ids = RequestUtil.getLongParams(req, "id");
		for (int i=0; i<ids.length; i++) {
			Comment.remove(ids[i]);
		}
		this.feedback("comment.delete", req, resp);
	}
	
	/**
	 * post a comment
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	public void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String author = RequestUtil.getRequiredParam(req, "author");
		author = Filter.length(author, 20);
		author = Filter.escape(author);
		String email = RequestUtil.getRequiredParam(req, "email");
		if ( ! Checker.isEmail(email) ) {
			throw new InteractException("email is'nt correct.");
		}
//		String url = RequestUtil.getStringParam(req, "url");
		String comment = RequestUtil.getRequiredParam(req, "content");
		comment = Filter.length(comment, 400);
		Long postId = RequestUtil.getLongParam(req, "postId");
		Comment comm = new Comment();
		comm.setUserName(author);
		comm.setEmail(email);
		comm.setContent(comment);
		comm.setPostId(postId);
		comm.save();
		this.feedfront("comment.add", req, resp);
	}
	
	public void approve(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		Long[] ids = RequestUtil.getLongParams(req, "id");
		for (int i=0; i<ids.length; i++) {
			Comment comm = Comment.load(ids[i]);
			comm.setPublished(true);
			comm.update();
		}
		this.feedback("comment.approve", req, resp);
	}
}
